package com.qiaofang.applet.common.base;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * mongodb增删改查，抽象实现
 *
 * @param <T> 实体类
 */
public abstract class MongoBaseService<T extends BaseDomain, ID> implements BaseService<T, ID> {

    private final MongoRepository<T, ID> repository;

    public MongoBaseService(MongoRepository<T, ID> repository) {
        Assert.notNull(repository, "repository must be not null");
        this.repository = repository;
    }

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Iterable<T> findAll(Sort sort) {
        return repository.findAll(sort);
    }

    @Override
    public Page<T> findAll(Pageable pageable) {
        return repository.findAll(pageable);
    }

    @Override
    public <S extends T> Optional<S> findOne(Example<S> example) {
        return repository.findOne(example);
    }

    @Override
    public <S extends T> Iterable<S> findAll(Example<S> example) {
        return repository.findAll(example);
    }

    @Override
    public <S extends T> Iterable<S> findAll(Example<S> example, Sort sort) {
        return repository.findAll(example, sort);
    }

    @Override
    public <S extends T> Page<S> findAll(Example<S> example, Pageable pageable) {
        return repository.findAll(example, pageable);
    }

    @Override
    public <S extends T> long count(Example<S> example) {
        return repository.count(example);
    }

    @Override
    public <S extends T> boolean exists(Example<S> example) {
        return repository.exists(example);
    }

    @Override
    public <S extends T> S save(S entity) {
        return repository.save(entity);
    }

    @Override
    public <S extends T> Iterable<S> saveAll(Iterable<S> entities) {
        return repository.saveAll(entities);
    }

    @Override
    public <S extends T> S insert(S entity) {
        return repository.insert(entity);
    }

    @Override
    public <S extends T> List<S> insert(Iterable<S> entities) {
        return repository.insert(entities);
    }

    @Override
    public Optional<T> findById(ID id) {
        return repository.findById(id);
    }

    @Override
    public boolean existsById(ID id) {
        return repository.existsById(id);
    }

    @Override
    public Iterable<T> findAllById(Iterable<ID> ids) {
        return repository.findAllById(ids);
    }

    @Override
    public long count() {
        return repository.count();
    }

    @Override
    public void deleteById(ID id) {
        repository.deleteById(id);
    }

    @Override
    public void delete(T entity) {
        repository.delete(entity);
    }

    @Override
    public void deleteAll(Iterable<? extends T> entities) {
        repository.deleteAll(entities);
    }

    public void updateById(T entity) {
        Class<? extends BaseDomain> entityClass = entity.getClass();
        Field[] fields = entityClass.getDeclaredFields();
        if (fields != null && fields.length > 0) {
            Query query = new Query(Criteria.where("id").is(entity.getId()));
            Update update = new Update();
            for (Field field : fields) {
                field.setAccessible(true);
                Object value = null;
                try {
                    PropertyDescriptor pd = new PropertyDescriptor(field.getName(), entityClass);
                    Method method = pd.getReadMethod();
                    value = method.invoke(entity);
                } catch (Exception e) {
                }
                if (value != null){
                    update.set(field.getName(), value);
                }
            }
            update.set("updateTime", new Date());
            setCityCode(update, entity);
            mongoTemplate.update(entityClass)
                    .matching(query)
                    .apply(update)
                    .withOptions(FindAndModifyOptions.options().returnNew(true))
                    .findAndModifyValue();
        }
    }

    /**
     * 如果城市code有值，同时更新城市code
     * @param update
     * @param entity
     */
    private void setCityCode(Update update, T entity) {
        try {
            PropertyDescriptor pd = new PropertyDescriptor("cityCode", entity.getClass());
            Method method = pd.getReadMethod();
            Object value = method.invoke(entity);
            if(StringUtils.isNotEmpty((String) value)){
                update.set("cityCode", value);
            }
        }catch (Exception e) {
        }
    }
}
